﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ECare.BUS.Data;
using ECare.BUS;

namespace ECare.Client.frms
{
    public partial class frmFomula : frmGridTemplate
    {
        public frmFomula()
        {
            InitializeComponent();

            this.Load += frmFomula_Load;
            this.grd.CellDoubleClick += grd_CellDoubleClick;
            this.btnEdit.Click += btnEdit_Click;
        }

        void btnEdit_Click(object sender, EventArgs e)
        {
            if (this.grd.SelectedRows.Count == 0)
                return;

            var entitye = this.grd.SelectedRows[0].DataBoundItem as FormulaInfo;
            var frm = new frmFomulaInfo();
            frm.entity = entitye;
            frm.Saved += frm_Saved;
            frm.ShowDialog();
        }

        void grd_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex < 0)
                return;
            var entitye = this.grd.Rows[e.RowIndex].DataBoundItem as FormulaInfo;
            var frm = new frmFomulaInfo();
            frm.entity = entitye;
            frm.Saved += frm_Saved;
            frm.ShowDialog();
        }

 

        BindingList<FormulaInfo> source { get; set; }

        void frmFomula_Load(object sender, EventArgs e)
        {
            this.LoadInformation(); 
            
            if (!CheckPermission(10))
                this.btnAdd.Enabled = false;

            if (!CheckPermission(11))
                this.btnEdit.Enabled = false;


        }

        private void LoadInformation()
        {
            source = new BindingList<FormulaInfo>(FormulaHelper.GetFormulaInfos());
            this.grd.DataSource = source;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var frm = new frmFomulaInfo();
            frm.entity = null;
            frm.Saved += frm_Saved;
            frm.ShowDialog();
            
        }

        void frm_Saved(object entity)
        {
            //throw new NotImplementedException();
            if (source == null)
                source = new BindingList<FormulaInfo>();
            var role = entity as FormulaInfo;
            var findresult = source.FirstOrDefault(a => a.FormulaId == role.FormulaId);
            if (findresult == null)
                this.source.Add(role);
        }
    }
}
